#include "user.h"
#include "wifi.h"
#include "mqtt.h"
#include "aht20.h"
#include "sen0291.h"
#include "esp_log.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"

static const char *TAG = "USER";

void user_task(void *pvParameters)
{
    // 先初始化I2C（通过AHT20初始化）
    ESP_LOGI(TAG, "Initializing I2C bus...");
    aht20_init();          // 初始化AHT20（同时初始化I2C总线）
    
    // 等待I2C总线稳定
    vTaskDelay(pdMS_TO_TICKS(500));
    
    sen0291_init();        // 初始化SEN0291（使用相同的I2C总线）

    while (1) {
        aht20_sensor_value_t aht20_sensor_value;
        sen0291_sensor_value_t sen0291_sensor_value;
        
        int aht20_status = aht20_read(&aht20_sensor_value);
        int sen0291_status = sen0291_read(&sen0291_sensor_value);
        
        char msg[128];
        if (aht20_status == 1 && sen0291_status == 1) {
            snprintf(msg, sizeof(msg), "{\"temp\":%.1f,\"hum\":%.1f,\"voltage\":%.2f,\"current\":%.2f}", aht20_sensor_value.temperature, aht20_sensor_value.humidity, sen0291_sensor_value.voltage,sen0291_sensor_value.current);
        } else {
            //测试数据
            snprintf(msg, sizeof(msg), "{\"voltage\":%.2f, \"current\":%.2f}", sen0291_sensor_value.voltage,sen0291_sensor_value.current);

        }
        if(MQTT_status == 1){
            mqtt_publish(MQTT_PUB_TOPIC, msg);
            ESP_LOGI(TAG, "Published: %s", msg);
        }
       

        vTaskDelay(pdMS_TO_TICKS(5000));
    }
}

void user_app_start(void)
{
    xTaskCreate(user_task, "user_task", 4096, NULL, 5, NULL);
}
